package com.lanvideo.controller;

import com.lanvideo.entity.Playlist;
import com.lanvideo.entity.PlaylistVideo;
import com.lanvideo.service.PlaylistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 播放列表控制器
 */
@RestController
@RequestMapping("/api/playlist")
public class PlaylistController {

    @Autowired
    private PlaylistService playlistService;

    /**
     * 创建播放列表
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createPlaylist(@RequestBody Playlist playlist, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 设置用户ID
            playlist.setUserId(userId);
            
            // 验证必填字段
            if (playlist.getName() == null || playlist.getName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "播放列表名称不能为空");
                return ResponseEntity.ok(result);
            }
            
            boolean success = playlistService.createPlaylist(playlist);
            
            if (success) {
                result.put("success", true);
                result.put("message", "播放列表创建成功");
            } else {
                result.put("success", false);
                result.put("message", "播放列表创建失败");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建播放列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 更新播放列表
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updatePlaylist(@RequestBody Playlist playlist, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 验证必填字段
            if (playlist.getId() == null) {
                result.put("success", false);
                result.put("message", "播放列表ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            if (playlist.getName() == null || playlist.getName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "播放列表名称不能为空");
                return ResponseEntity.ok(result);
            }
            
            // 检查播放列表是否属于当前用户
            if (!playlistService.isPlaylistOwner(playlist.getId(), userId)) {
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            boolean success = playlistService.updatePlaylist(playlist);
            
            if (success) {
                result.put("success", true);
                result.put("message", "播放列表更新成功");
            } else {
                result.put("success", false);
                result.put("message", "播放列表更新失败");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新播放列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 删除播放列表
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deletePlaylist(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 检查播放列表是否属于当前用户
            if (!playlistService.isPlaylistOwner(id, userId)) {
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            boolean success = playlistService.deletePlaylist(id);
            
            if (success) {
                result.put("success", true);
                result.put("message", "播放列表删除成功");
            } else {
                result.put("success", false);
                result.put("message", "播放列表删除失败");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除播放列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 根据ID获取播放列表
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getPlaylistById(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Playlist playlist = playlistService.getPlaylistById(id);
            
            if (playlist == null) {
                result.put("success", false);
                result.put("message", "播放列表不存在");
                return ResponseEntity.ok(result);
            }
            
            // 检查权限：公开播放列表或用户自己的播放列表
            Integer userId = (Integer) session.getAttribute("userId");
            if (!playlist.getIsPublic() && (userId == null || !playlist.getUserId().equals(userId))) {
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            result.put("success", true);
            result.put("playlist", playlist);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取播放列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取用户的播放列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserPlaylists(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的播放列表
        if (!currentUserId.equals(userId)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<Playlist> playlists = playlistService.getUserPlaylists(userId);
            result.put("success", true);
            result.put("playlists", playlists);
            result.put("count", playlists.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取播放列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取公开的播放列表
     */
    @GetMapping("/public")
    public ResponseEntity<Map<String, Object>> getPublicPlaylists() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Playlist> playlists = playlistService.getPublicPlaylists();
            result.put("success", true);
            result.put("playlists", playlists);
            result.put("count", playlists.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取公开播放列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 搜索播放列表
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchPlaylists(@RequestParam String keyword) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Playlist> playlists = playlistService.searchPlaylists(keyword);
            result.put("success", true);
            result.put("playlists", playlists);
            result.put("count", playlists.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索播放列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 添加视频到播放列表
     */
    @PostMapping("/{playlistId}/add-video")
    public ResponseEntity<Map<String, Object>> addVideoToPlaylist(@PathVariable Integer playlistId, 
                                                                @RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            Integer videoId = (Integer) request.get("videoId");
            
            if (videoId == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            // 检查播放列表是否属于当前用户
            if (!playlistService.isPlaylistOwner(playlistId, userId)) {
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            boolean success = playlistService.addVideoToPlaylist(playlistId, videoId);
            
            if (success) {
                result.put("success", true);
                result.put("message", "视频已添加到播放列表");
            } else {
                result.put("success", false);
                result.put("message", "视频已在播放列表中");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加视频失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 从播放列表移除视频
     */
    @DeleteMapping("/{playlistId}/remove-video/{videoId}")
    public ResponseEntity<Map<String, Object>> removeVideoFromPlaylist(@PathVariable Integer playlistId, 
                                                                      @PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 检查播放列表是否属于当前用户
            if (!playlistService.isPlaylistOwner(playlistId, userId)) {
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            boolean success = playlistService.removeVideoFromPlaylist(playlistId, videoId);
            
            if (success) {
                result.put("success", true);
                result.put("message", "视频已从播放列表移除");
            } else {
                result.put("success", false);
                result.put("message", "视频不在播放列表中");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "移除视频失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取播放列表中的所有视频
     */
    @GetMapping("/{playlistId}/videos")
    public ResponseEntity<Map<String, Object>> getPlaylistVideos(@PathVariable Integer playlistId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Playlist playlist = playlistService.getPlaylistById(playlistId);
            
            if (playlist == null) {
                result.put("success", false);
                result.put("message", "播放列表不存在");
                return ResponseEntity.ok(result);
            }
            
            // 检查权限：公开播放列表或用户自己的播放列表
            Integer userId = (Integer) session.getAttribute("userId");
            if (!playlist.getIsPublic() && (userId == null || !playlist.getUserId().equals(userId))) {
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            List<PlaylistVideo> videos = playlistService.getPlaylistVideos(playlistId);
            result.put("success", true);
            result.put("videos", videos);
            result.put("count", videos.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取播放列表视频失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
}
